package com.store.app.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.store.app.BaseActivity;
import com.store.app.ExitApplication;
import com.store.app.R;
import com.store.app.bean.CouponGoCashBean;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.utils.MoneyUtil;
import com.store.app.utils.Utils;

import org.json.JSONObject;

import java.math.BigDecimal;

import de.greenrobot.event.EventBus;

/**
 * 提现页面--佣金
 * Created by Administrator on 2016/10/31.
 */
public class CommissionWithdrawActivity extends BaseActivity implements IOnHttpListener, View.OnClickListener {

    private ImageView public_ll_return;
    private TextView tvTitle;
    private RelativeLayout rl_parent;//标题栏根布局

    private TextView tv_bankname;//银行卡名称
    private TextView tv_bankno;//银行卡号码
    private TextView tv_canuse_money;//可提金额

    /**输入的金额*/
    private TextView money;
    private TextView tv_service_fee;//服务费

    private TextView tv_right_join;//进入箭头
    private TextView cancel;//取消按钮
    private TextView submit;//确认按钮

    private String bankname;//传递过来的银行卡名称
    private String bankno;//传递过来的银行卡号码
    private String usable_cash_balance;//传递过来的可提金额

    private NetRequest netRequest;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_commission_withdraw);
        ExitApplication.getInstance().addActivity(this);
        init();
        initView();
        initListener();
        initData();
    }

    private void init(){
        getIntentData();
        netRequest = new NetRequest(this);
    }

    private void getIntentData() {
        bankname = getIntent().getStringExtra("bank_name");
        bankno = getIntent().getStringExtra("bank_no");
        usable_cash_balance = getIntent().getStringExtra("usable_commission");
    }

    private void initView() {
        public_ll_return = (ImageView) findViewById(R.id.public_ll_return);
        tvTitle = (TextView) findViewById(R.id.tvTitle);
        rl_parent = (RelativeLayout) findViewById(R.id.rl_parent);

        tv_bankname = (TextView) findViewById(R.id.tv_bankname);
        tv_bankno = (TextView) findViewById(R.id.tv_bankno);
        tv_canuse_money = (TextView) findViewById(R.id.tv_canuse_money);
        tv_right_join = (TextView) findViewById(R.id.tv_right_join);

        //请输入金额
        money = (TextView) findViewById(R.id.payee_amount);
        money.setHint("请输入提现金额");
        tv_service_fee = (TextView) findViewById(R.id.tv_service_fee);

        cancel = (TextView) findViewById(R.id.cancel);
        submit = (TextView) findViewById(R.id.submit);
    }

    private void initListener() {
        public_ll_return.setOnClickListener(this);

        tv_right_join.setOnClickListener(this);
        cancel.setOnClickListener(this);
        submit.setOnClickListener(this);
    }

    private void initData() {
        initTitleBar();
        initBankCardInfo();
        initKeyboardLayout();
    }

    private void initTitleBar() {
        tvTitle.setText("提现");
        rl_parent.setBackground(null);
    }

    private void initBankCardInfo() {
        tv_bankname.setText(bankname);
        tv_bankno.setText(bankno);
        tv_canuse_money.setText("¥ " + MoneyUtil.formatMoney(usable_cash_balance));
    }

    private void initKeyboardLayout() {

        /**显示输入的金额的TextView*/
        TextView payee_amount = (TextView) findViewById(R.id.payee_amount);

        TextView pay_one = (TextView) findViewById(R.id.pay_one);
        pay_one.setOnClickListener(myListener);

        TextView pay_two = (TextView) findViewById(R.id.pay_two);
        pay_two.setOnClickListener(myListener);

        TextView pay_three = (TextView) findViewById(R.id.pay_three);
        pay_three.setOnClickListener(myListener);

        TextView pay_four = (TextView) findViewById(R.id.pay_four);
        pay_four.setOnClickListener(myListener);

        TextView pay_five = (TextView) findViewById(R.id.pay_five);
        pay_five.setOnClickListener(myListener);

        TextView pay_six = (TextView) findViewById(R.id.pay_six);
        pay_six.setOnClickListener(myListener);

        TextView pay_seven = (TextView) findViewById(R.id.pay_seven);
        pay_seven.setOnClickListener(myListener);

        TextView pay_eight = (TextView) findViewById(R.id.pay_eight);
        pay_eight.setOnClickListener(myListener);

        TextView pay_nine = (TextView) findViewById(R.id.pay_nine);
        pay_nine.setOnClickListener(myListener);

        TextView pay_zero = (TextView) findViewById(R.id.pay_zero);
        pay_zero.setOnClickListener(myListener);

        TextView pay_space = (TextView) findViewById(R.id.pay_space);//小数点
        pay_space.setOnClickListener(myListener);

        TextView pay_del = (TextView) findViewById(R.id.pay_del);
        pay_del.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {

                int index = money.getSelectionStart();
                if (index != 0) {
                    moneytext = money.getText().toString();
                    if (!TextUtils.isEmpty(moneytext)) {
                        moneytext = moneytext.substring(0, moneytext.length() - 1);
                        money.setText(moneytext);
                    }
                }
            }
        });

        payee_amount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.length() > 0) {//TextView有显示内容text

                    money.setTextSize(TypedValue.COMPLEX_UNIT_SP,29);
                    String formatServiceFee = MoneyUtil.fnum.format(Double.parseDouble(editable.toString()) * 0.05);
                    tv_service_fee.setText("(服务费" + formatServiceFee + "元)");
                    tv_service_fee.setTextSize(TypedValue.COMPLEX_UNIT_SP,11);

                    submit.setBackgroundResource(R.drawable.border5px_blue_00c3e2);
                    submit.setTextColor(Color.parseColor("#ffffff"));
                } else {//TextView无显示内容text

                    money.setTextSize(TypedValue.COMPLEX_UNIT_SP,19);

                    tv_service_fee.setText("");
                    tv_service_fee.setTextSize(TypedValue.COMPLEX_UNIT_SP,12);

                    submit.setBackgroundResource(R.drawable.border_gray_80ffffff);
                    submit.setTextColor(Color.parseColor("#333333"));
                }
            }
        });
    }

    /**输入的金额*/
    private String moneytext;
    View.OnClickListener myListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            moneytext = money.getText().toString();
            if (moneytext.contains(".")) {
                String[] tempS = moneytext.split("\\.");
                if (tempS.length > 1) {
                    int resultNum = tempS[1].length();
                    if (resultNum > 1) {
                        return;
                    }
                }
            }
            switch (v.getId()) {
                case R.id.pay_space:
                    moneytext = money.getText().toString();
                    if (!moneytext.contains(".")) {
                        if (moneytext.equals("")) {
                            input_digit("0.");
                        } else {
                            input_digit(".");
                        }
                    }
                    break;

                case R.id.pay_zero:
                    input_digit("0");

                    break;
                case R.id.pay_one:
                    input_digit("1");

                    break;
                case R.id.pay_two:
                    input_digit("2");

                    break;
                case R.id.pay_three:
                    input_digit("3");

                    break;
                case R.id.pay_four:
                    input_digit("4");

                    break;
                case R.id.pay_five:
                    input_digit("5");

                    break;
                case R.id.pay_six:
                    input_digit("6");

                    break;
                case R.id.pay_seven:
                    input_digit("7");

                    break;
                case R.id.pay_eight:
                    input_digit("8");

                    break;
                case R.id.pay_nine:
                    input_digit("9");

                    break;
                default:
                    break;
            }
        }
    };

    private void input_digit(String digit) {
        moneytext = money.getText().toString();
        if (moneytext.indexOf(".") != -1) {
            //获取小数点的位置
            int num = 0;
            num = moneytext.indexOf(".");
            if (moneytext.length() - num > 2) {

            } else {
                moneytext = moneytext + digit;
            }
        } else {
            moneytext = moneytext + digit;
        }
        money.setText(moneytext);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.public_ll_return:
                finish();
                break;
            case R.id.tv_right_join:
                Intent intent = new Intent(CommissionWithdrawActivity.this,BindBalanceActivity.class);
                startActivity(intent);
                break;
            case R.id.cancel:
                money.setText("");
                break;
            case R.id.submit:
                // TODO: 2017/9/4 0004
                netRequest.requestUsableCashBalanceFind(1);//查询佣金可提金额
                break;
        }
    }

    private ProgressDialog progressBar;

    @Override
    public void onAfinalFail() {
        if (progressBar != null) {
            progressBar.dismiss();
        }
        showToast("请检查本地网络");
    }

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
        //获取佣金可提金额
        if (requestId == 1) {
            try {
                JSONObject jsonObject = new JSONObject(result);
                // TODO: 2017/9/4 0004
                usable_cash_balance = jsonObject.getString("usable_cash_balance");
                tv_canuse_money.setText("¥ " + usable_cash_balance);
                Log.v("zyl", "设置可用金额：" + usable_cash_balance);

                if (!TextUtils.isEmpty(moneytext)) {

                    if (Double.parseDouble(moneytext) >= 0) {

                        if(Utils.isFastClick()){
                            Log.v("zyl","快速点击了");
                            return;
                        }

                        if (!MoneyUtil.moneyBigThan(usable_cash_balance, "0")) {
                            Toast.makeText(CommissionWithdrawActivity.this, "可用佣金余额不足",
                                    Toast.LENGTH_LONG).show();
                            return;
                        }

                        if (!TextUtils.isEmpty(moneytext)) {
                            //可用余额与提现金额做比较
                            if (!MoneyUtil.moneyComp(usable_cash_balance, moneytext)) {
                                Toast.makeText(CommissionWithdrawActivity.this, "可用佣金余额不足",
                                        Toast.LENGTH_LONG).show();
                                return;
                            }
                            //提现金额是否大于100
                            Log.v("zyl", "**:" + !MoneyUtil.moneyComp(moneytext, "100"));
                            if (!MoneyUtil.moneyComp(moneytext, "100")) {
                                Toast.makeText(CommissionWithdrawActivity.this, "提现金额100元起！",
                                        Toast.LENGTH_LONG).show();
                                return;
                            }
                            showLoading();
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (requestId == 4) {
            if (progressBar != null) {
                progressBar.dismiss();
            }
            Toast.makeText(CommissionWithdrawActivity.this, "提现申请已被受理，预计将在3个工作日转账至您注册时提供的银行账户内。如果有问题，每天惠客服将主动联系您，谢谢合作！",
                    Toast.LENGTH_LONG).show();
            EventBus.getDefault().post(new CouponGoCashBean(2));//提现成功后，刷新佣金界面数据

            finish();
        }
    }

    @Override
    public void onExecuteFail(int requestId, String msg) {
        if (progressBar != null) {
            progressBar.dismiss();
        }
        Toast.makeText(CommissionWithdrawActivity.this, msg,
                Toast.LENGTH_LONG).show();
    }

    /**
     * 显示加载等待进度圈
     */
    public void showLoading() {
        progressBar = new ProgressDialog(CommissionWithdrawActivity.this);
        progressBar.setCancelable(false);
        progressBar.setMessage("提现中...");
        progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressBar.setProgress(0);
        progressBar.setMax(100);
        progressBar.show();
        // TODO: 2017/9/4 0004
        netRequest.requestWithdraw(4, moneytext);
        money.setText("");
    }

    /**
     * 在Activity中启动当前Activity
     *
     * @param activity 启动Activity
     * @param bankName 银行卡名称
     * @param bankNo 银行卡卡号
     * @param usableCommission 佣金可提金额
     */
    public static void show(Activity activity, String bankName, String bankNo, String usableCommission) {
        Intent intent = new Intent(activity, CommissionWithdrawActivity.class);
        intent.putExtra("bank_name",bankName);
        intent.putExtra("bank_no",bankNo);
        intent.putExtra("usable_commission",usableCommission);
        activity.startActivity(intent);
    }

}
